﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class administration_listLegalPersons : System.Web.UI.Page
{
    private string IDEN, UPDATEPARAM, NEWPARAM, MESSAGEPARAM, DELETEPARAM;
    private const string IDPAGE = "1";

    protected void Page_Load(object sender, EventArgs e)
    {
        //Check the status of the session
        STATE_SESSION();

        //Verify the view that corresponds show
        if (!Page.IsPostBack)
        {
            string flgInsert = Request.Cookies.Get("flgInsert").Value;
            string flgUpdate = Request.Cookies.Get("flgUpdate").Value;
            string flgDelete = Request.Cookies.Get("flgDelete").Value;

            this.IDEN = Request.Params.Get("id");
            this.NEWPARAM = Request.Params.Get("new");
            this.UPDATEPARAM = Request.Params.Get("update");
            this.MESSAGEPARAM = Request.Params.Get("message");
            this.DELETEPARAM = Request.Params.Get("delete");

            if (this.NEWPARAM != null)
            {
                MLegalPersons.ActiveViewIndex = 1;
            }
            else
            {
                if (this.UPDATEPARAM != null)
                {
                    MLegalPersons.ActiveViewIndex = 2;
                }
                else
                {
                    if (this.MESSAGEPARAM != null)
                    {
                        MLegalPersons.ActiveViewIndex = 3;
                        String nameupdate = Request.Params.Get("nameupdate");
                        String namenew = Request.Params.Get("namenew");
                        String removal = Request.Params.Get("removal");
                        if (namenew != null )
                        {
                            this.lblMessage.Text = "Se ha registrado con exito a: " + namenew;
                        }
                        else
                        {
                            if(nameupdate != null)
                            {
                                this.lblMessage.Text = "La modificacion ha sido exitosa.";
                            }
                            else
                            {
                                if (removal != null)
                                {
                                    if (removal.Equals("yes"))
                                    {
                                        this.lblMessage.Text = "La eliminacion ha sido exitosa.";
                                    }
                                    else
                                    {
                                        this.lblMessage.Text = "El registro esta siendo usado, por este motivo no puede ser eliminado.";
                                    }
                                }
                            }                            
                        }
                    }
                    else
                    {
                        if (this.DELETEPARAM != null)
                        {
                            this.DeleteRecord(this.IDEN);
                        }
                        MLegalPersons.ActiveViewIndex = 0;
                    }
                }
            }
            intPageSize.Text = "10"; //Here indicates the size of the page
            intCurrIndex.Text = "0";
            Bind(this.txtSearch.Text);
            //Disable the checks after loading the datalist
            UpdateInsertDelete(flgUpdate, flgInsert, flgDelete);
            //Built the menu according to user roles
            BuildMenu();
        }
    }

    //Method to verify the status of the current session
    public void STATE_SESSION()
    {
        if (!Page.IsPostBack)
        {
            HttpCookie state = Request.Cookies.Get("state");
            if (state == null)
                Response.Redirect("../index.aspx");
        }
    }

    //Method to verify the user's role
    private void UpdateInsertDelete(string update, string insert, string delete)
    {
        if (!insert.Equals("1"))
        {
            lnkNew.Enabled = false;
        }
        if(!update.Equals("2")){
            foreach (DataListItem item in DataList1.Items)
            {
                HyperLink hp = null;
                hp = (HyperLink)item.FindControl("lnkUpdate");
                if (hp != null)
                {
                    hp.Enabled = false;
                }
            }
        }
        if (!delete.Equals("3"))
        {
            foreach (DataListItem item in DataList1.Items)
            {
                HyperLink hp = null;
                hp = (HyperLink)item.FindControl("lnkDelete");
                if (hp != null)
                {
                    hp.Enabled = false;
                }
            }
        }
    }

    //Method to build menu
    private void BuildMenu()
    {
        string programName = Request.Cookies.Get("programName").Value;
        char[] delimiterChars = { ',' };
        string[] vectorProgramName = programName.Split(delimiterChars);
        string welcome = "";
        string segurity = "";
        string system = "";
        string parameters = "";
        string people = "";
        string operations = "";
        string reports = "";
        string profile = "";
        for (int i = 0; i < vectorProgramName.Length; i++)
        {
            switch (Convert.ToInt32(vectorProgramName[i]))
            {
                case 1:
                    people += "<li><a class=\"item\" href=\"listNaturalPersons.aspx\"> - Personas Naturales</a></li>";
                    break;
                case 2:
                    people += "<li><a class=\"item\" href=\"listLegalPersons.aspx\"> - Personas Legales</a></li>";
                    break;
                case 3:
                    welcome += "<li><a class=\"item\" href=\"index.aspx\"> - Bienvenido</a></li>";
                    break;
                case 4:
                    parameters += "";
                    break;
                case 5:
                    system += "<li><a class=\"item\" href=\"listLogTransaction.aspx\"> - Log de Transacciones</a></li>";
                    break;
                case 6:
                    operations += "<li><a class=\"item\" href=\"listNews.aspx\"> - Boletines</a></li>";
                    break;
                case 7:
                    operations += "<li><a class=\"item\" href=\"listClient.aspx\"> - Clientes</a></li>";
                    break;
                case 8:
                    segurity += "<li><a class=\"item\" href=\"listProfiles.aspx\"> - Perfiles</a></li>";
                    break;
                case 9:
                    system += "<li><a class=\"item\" href=\"listPrograms.aspx\"> - Programas</a></li>";
                    break;
                case 10:
                    operations += "<li><a class=\"item\" href=\"listCourse.aspx\"> - Cursos</a></li>";
                    break;
                case 11:
                    segurity += "<li><a class=\"item\" href=\"listRoles.aspx\"> - Roles</a></li>";
                    break;
                case 12:
                    segurity += "<li><a class=\"item\" href=\"listUsers.aspx\"> - Usuarios</a></li>";
                    break;
                case 13:
                    reports += "<li><a class=\"item\" href=\"reports.aspx\"> - Clientes por tipo de Servicio</a></li>";
                    break;
                case 14:
                    system += "<li><a class=\"item\"href=\"listWorkArea.aspx\"> - Areas</a></li>";
                    break;
                case 15:
                    parameters += "<li><a class=\"item\"href=\"listMode.aspx\"> - Modalidades</a></li>";
                    break;
                case 16:
                    parameters += "<li><a class=\"item\"href=\"listProfession.aspx\"> - Profesiones</a></li>";
                    break;
                case 17:
                    operations += "<li><a class=\"item\"href=\"listPublicity.aspx\"> - Publicidades</a></li>";
                    break;
                case 18:
                    operations += "<li><a class=\"item\"href=\"listQuestionAnswer.aspx\"> - Consultas del Cliente</a></li>";
                    break;
                case 19:
                    parameters += "<li><a class=\"item\"href=\"listService.aspx\"> - Servicios</a></li>";
                    break;                
                case 21:
                    operations += "<li><a class=\"item\"href=\"listServiceProfileClient.aspx\"> - Perfiles de Clientes</a></li>";
                    break;
                case 22:
                    operations += "<li><a class=\"item\"href=\"listSponsor.aspx\"> - Auspiciadores</a></li>";
                    break;
                case 23:
                    parameters += "<li><a class=\"item\"href=\"listYear.aspx\"> - Gestiones</a></li>";
                    break;
                case 24:
                    profile += "<li><a class=\"item\"href=\"listProfileClientService.aspx\"> - Servicios</a></li>";
                    break;
                case 25:
                    profile += "<li><a class=\"item\"href=\"listProfileClientCourse.aspx\"> - Cursos</a></li>";
                    break;
                case 26:
                    operations += "<li><a class=\"item\"href=\"listClientCourse.aspx\"> - Cursos del Cliente</a></li>";
                    break;
                case 27:
                    profile += "<li><a class=\"item\"href=\"listProfileQA.aspx\"> - Consultas</a></li>";
                    break;
            }
        }
        lblMenu.Text = "<div class=\"left\"><ul class=\"title\"><li>Menu Administrativo</li></ul><ul id=\"menu\"><li>";
        lblMenu.Text += "<a href=\"#\">Bienvenido</a><ul>";
        lblMenu.Text += welcome;
        lblMenu.Text += "</ul></li>";
        if (!segurity.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Seguridad</a><ul>";
            lblMenu.Text += segurity;
            lblMenu.Text += "</ul></li>";
        }
        if (!system.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion del Sistema</a><ul>";
            lblMenu.Text += system;
            lblMenu.Text += "</ul></li>";
        }
        if (!parameters.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Parametros</a><ul>";
            lblMenu.Text += parameters;
            lblMenu.Text += "</ul></li>";
        }
        if (!people.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Personas</a><ul>";
            lblMenu.Text += people;
            lblMenu.Text += "</ul></li>";
        }
        if (!operations.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Operaciones</a><ul>";
            lblMenu.Text += operations;
            lblMenu.Text += "</ul></li>";
        }
        if (!profile.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Perfil del Cliente</a><ul>";
            lblMenu.Text += profile;
            lblMenu.Text += "</ul></li>";
        }
        if (!reports.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Reportes</a><ul>";
            lblMenu.Text += reports;
            lblMenu.Text += "</ul></li>";
        }
        lblMenu.Text += "<li><a href=\"../index.aspx\">Salir</a></li>";
        lblMenu.Text += "</ul></div>";
    }

    //Method to enable calendar
    protected void PopCalendar_SelectionChanged(object sender, EventArgs e)
    {
        this.Validate("RJS.PopCalendars");
    }

    //Method to cancel the view NEW
    protected void lnkCancel_Click(object sender, EventArgs e)
    {
        MLegalPersons.ActiveViewIndex = 0;
    }

    //Method to cancel the view UPDATE
    protected void lnkCancel_Click1(object sender, EventArgs e)
    {
        MLegalPersons.ActiveViewIndex = 0;
    }

    #region Pager

    //Method to query data and create the pager
    private void Bind(String txtSearch)
    {
        DataSet objDS = new DataSet();
        clsPLegal objPNatural = new clsPLegal();
        
        if (!Page.IsPostBack)
        {
            objDS = objPNatural.SeeAllTheRecords(0, 0, txtSearch);
            intRecordCount.Text = objDS.Tables[0].Rows.Count + "";
            objDS = null;
            objDS = new DataSet();
        }

        if (intCurrIndex.Text.Equals("0"))
        {
            hrefPrevious.Visible = false;
        }
        else
        {
            hrefPrevious.Visible = true;
        }

        objDS = objPNatural.SeeAllTheRecords(Int32.Parse(intCurrIndex.Text), Int32.Parse(intPageSize.Text), txtSearch);        

        DataList1.DataSource = objDS.Tables[0].DefaultView;
        DataList1.DataBind();
        PrintStatus();
    }

    //Method to navigate to the first page of pager
    public void ShowFirst(object sender, EventArgs e)
    {
        intCurrIndex.Text = "0";
        Bind(this.txtSearch.Text);
    }

    //Method to navigate to the previous page in the pager
    public void ShowPrevious(object sender, EventArgs e)
    {
        intCurrIndex.Text = (Int32.Parse(intCurrIndex.Text) - Int32.Parse(intPageSize.Text)) + "";
        if (Int32.Parse(intCurrIndex.Text) < 0)
        {
            intCurrIndex.Text = "0";
        }
        Bind(this.txtSearch.Text);
    }

    //Method to navigate to the next page in the pager
    public void ShowNext(object sender, EventArgs e)
    {
        if ((Int32.Parse(intCurrIndex.Text) + 1) < Int32.Parse(intRecordCount.Text))
        {
            intCurrIndex.Text = (Int32.Parse(intCurrIndex.Text) + Int32.Parse(intPageSize.Text)) + "";
        }
        Bind(this.txtSearch.Text);
    }

    //Method to navigate to the last page of the pager
    public void ShowLast(object sender, EventArgs e)
    {
        int tmpInt = 0;
        tmpInt = Int32.Parse(intRecordCount.Text) % Int32.Parse(intPageSize.Text);
        if (tmpInt > 0)
        {
            intCurrIndex.Text = (Int32.Parse(intRecordCount.Text) - tmpInt) + "";
        }
        else
        {
            intCurrIndex.Text = (Int32.Parse(intRecordCount.Text) - Int32.Parse(intPageSize.Text)) + "";
        }
        Bind(this.txtSearch.Text);
    }

    //Method to generate the data pager navigation
    private void PrintStatus()
    {
        lblTotal.Text = "Total de Registros:<b> " + intRecordCount.Text + "</b>";
        lblShowing.Text = "Mostrando Pagina:<b> ";
        lblShowing.Text += ((Int32.Parse(intCurrIndex.Text) / Int32.Parse(intPageSize.Text)) + 1) + "";
        lblShowing.Text += "</b> de <b>";

        if ((Int32.Parse(intRecordCount.Text) % Int32.Parse(intPageSize.Text)) > 0)
        {
            lblShowing.Text += ((Int32.Parse(intRecordCount.Text) / Int32.Parse(intPageSize.Text)) + 1) + "";
        }
        else
        {
            lblShowing.Text += (Int32.Parse(intRecordCount.Text) / Int32.Parse(intPageSize.Text)) + "";
        }
        lblShowing.Text += "</b>";
    }
    #endregion

    //To search method
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Bind(this.txtSearch.Text);
    }

    //Method to insert a record in the view NEW
    protected void lnkInsert_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            clsPerson objPerson = new clsPerson();
            objPerson.IFlgTypePerson = 1;
            int idPerson = objPerson.Insert();

            clsPLegal objPLegal = new clsPLegal();
            objPLegal.ID = idPerson;
            objPLegal.INIT = Convert.ToInt32(txtNIT.Text);            
            objPLegal.IPhone1 = Convert.ToInt32(txtPhone1.Text);
            if (txtPhone2.Text.Length > 0)
                objPLegal.IPhone2 = Convert.ToInt32(txtPhone2.Text);
            else
                objPLegal.IPhone2 = 0;
            objPLegal.IdAgent = Convert.ToInt32(cbPNatural.SelectedValue);
            objPLegal.IdWorkArea = Convert.ToInt32(cbWorkArea.SelectedValue);
            objPLegal.SName = txtName.Text;
            objPLegal.SAddress = txtAddress.Text;
            objPLegal.SEmail = txtEmail.Text;
            objPLegal.Insert();

            Response.Redirect("listLegalPersons.aspx?message=yes&namenew=" + txtName.Text);
        }
        else
        {
            lblMsgValidatorNew.Text = "Algunos campos no son validos.";
        }        
    }

    //Method to return the view according to the message
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        if ((Request.Params.Get("nameupdate") != null) || (Request.Params.Get("removal") != null))
            Response.Redirect("listLegalPersons.aspx");
        else
            Response.Redirect("listLegalPersons.aspx?new=yes");
    }

    //Method to update a record in the view UPDATE
    protected void lnkUpdate_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            HiddenField fhidID = (HiddenField)frmvUpdateLegalPerson.FindControl("hidID");
            TextBox ftxtName = (TextBox)frmvUpdateLegalPerson.FindControl("txtName");
            TextBox ftxtEmail = (TextBox)frmvUpdateLegalPerson.FindControl("txtEmail");
            TextBox ftxtNIT = (TextBox)frmvUpdateLegalPerson.FindControl("txtNIT");
            DropDownList fcbPNatural = (DropDownList)frmvUpdateLegalPerson.FindControl("cbPNatural");
            DropDownList fcbWorkArea = (DropDownList)frmvUpdateLegalPerson.FindControl("cbWorkArea");
            TextBox ftxtAddress = (TextBox)frmvUpdateLegalPerson.FindControl("txtAddress");
            TextBox ftxtPhone1 = (TextBox)frmvUpdateLegalPerson.FindControl("txtPhone1");
            TextBox ftxtPhone2 = (TextBox)frmvUpdateLegalPerson.FindControl("txtPhone2");

            clsPLegal objPNatural = new clsPLegal();
            objPNatural.ID = Convert.ToInt32(fhidID.Value);
            objPNatural.INIT = Convert.ToInt32(ftxtNIT.Text);
            objPNatural.IPhone1 = Convert.ToInt32(ftxtPhone1.Text);
            if (ftxtPhone2.Text.Length > 0)
                objPNatural.IPhone2 = Convert.ToInt32(ftxtPhone2.Text);
            else
                objPNatural.IPhone2 = 0;
            objPNatural.IdAgent = Convert.ToInt32(fcbPNatural.SelectedValue);
            objPNatural.IdWorkArea = Convert.ToInt32(fcbWorkArea.SelectedValue);
            objPNatural.SName = ftxtName.Text;
            objPNatural.SAddress = ftxtAddress.Text;
            objPNatural.SEmail = ftxtEmail.Text;
            objPNatural.Update();

            Response.Redirect("listLegalPersons.aspx?message=yes&nameupdate=" + ftxtName.Text);
        }
        else
        {
            lblMsgValidatorNew.Text = "Algunos campos no son validos.";
        }
    }

    //Method for the disposal of records
    private void DeleteRecord(String id)
    {
        clsClient objClient = new clsClient();
        DataSet dtClient = objClient.ConsultPLegalID(id);

        clsSponsor objSponsor = new clsSponsor();
        DataSet dtSponsor = objSponsor.ConsultPLegalID(id);

        clsPublicity objPublicity = new clsPublicity();
        DataSet dtPublicity = objPublicity.ConsultPLegalID(id);

        if ((dtClient.Tables[0].Rows.Count == 0) && (dtSponsor.Tables[0].Rows.Count == 0) && (dtPublicity.Tables[0].Rows.Count == 0))
        {
            clsPLegal objPLegal = new clsPLegal();
            objPLegal.ID = Convert.ToInt32(id);
            objPLegal.Delete();            

            clsPerson objPerson = new clsPerson();
            objPerson.ID = Convert.ToInt32(id);
            objPerson.Delete();
            Response.Redirect("listLegalPersons.aspx?message=yes&removal=yes");
        }
        else
        {
            Response.Redirect("listLegalPersons.aspx?message=yes&removal=no");
        }
    }
}